package com.jnu.myfirstapplication.Adapter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.jnu.myfirstapplication.BookListMainActivity;
import com.jnu.myfirstapplication.R;
import com.jnu.myfirstapplication.data.Book;
import com.jnu.myfirstapplication.recycleItem.ItemTouchCallBack;

import java.util.ArrayList;
import java.util.List;

public class BookRecycleViewAdapter extends RecyclerView.Adapter<BookRecycleViewAdapter.ViewHolder> implements Filterable,View.OnClickListener,ItemTouchCallBack.OnItemTouchListener {
    private List<Book> bookList;
    private OnItemClickListener onItemClickListener;
    private RecyclerView recyclerView;
    private Context context;
    private static final int MENU_ID_UPDATE = 2;
    private static final int MENU_ID_DELETE = 3;
    public BookRecycleViewAdapter(Context context,List<Book> bookList) {
        this.context=context;
        this.bookList = bookList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.book, viewGroup, false);

        //为View设置单击事件
        view.setOnClickListener(this);
        DataViewHolder viewHolder = new DataViewHolder(view);

        //使用代码设置宽高（xml布局设置无效时）
//        view.setLayoutParams(new RecyclerView.LayoutParams(
//                ViewGroup.LayoutParams.MATCH_PARENT,
//                ViewGroup.LayoutParams.WRAP_CONTENT));
        return new ViewHolder(view);
    }



    public static class DataViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        public DataViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(R.id.textView_item_caption);
        }
        public int getId(){
            return itemView.getId();
        }
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        Book book = BookListMainActivity.mFilterList.get(position);
        Drawable drawable = null;
        try {
            String path = "/sdcard/Pictures/book/book" + book.getCoverResourceId() + ".jpg";
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            drawable = new BitmapDrawable(context.getResources(), bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        holder.getId().setImageDrawable(drawable);
        holder.getName().setText(book.getTitle());
        if (book.getAuthor().length() != 0) {
            holder.getDescribe().setText("" + book.getAuthor() + " 著， " + book.getPublisher());
        } else {
            holder.getDescribe().setText("" + book.getPublisher());
        }
        holder.getPubDate().setText("" + book.getPubDate());
    }

    @Override
    public int getItemCount() {
        //注意这里需要是过滤后的list
        return BookListMainActivity.mFilterList.size();
    }



    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
        TextView name;
        TextView describe;
        TextView pubDate;

        public TextView getPubDate() {
            return pubDate;
        }

        public TextView getDescribe() {
            return describe;
        }


        ImageView id;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            id = itemView.findViewById(R.id.image_view_book_cover);
            name = itemView.findViewById(R.id.text_view_book_title);
            describe = itemView.findViewById(R.id.text_view_book_describe);
            pubDate = itemView.findViewById(R.id.text_view_book_pubDate);

            itemView.setOnCreateContextMenuListener(this);
        }

        public TextView getName() {
            return name;
        }

        public ImageView getId() {
            return id;
        }

        @Override
        public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
//            contextMenu.add(0, MENU_ID_UPDATE, getAdapterPosition(), "Update" + getAdapterPosition());
//            contextMenu.add(0, MENU_ID_DELETE, getAdapterPosition(), "Delete" + getAdapterPosition());
        }

    }


    private List<Book> mSourceList = new ArrayList<>();

    public void appendList(ArrayList<Book> sourcelist) {
        mSourceList = sourcelist;
        //这里需要初始化filterList
        BookListMainActivity.mFilterList = sourcelist;
    }


    //重写getFilter()方法
    @Override
    public Filter getFilter() {
        return new Filter() {
            //执行过滤操作
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                BookListMainActivity.bias = new ArrayList<>();
                BookListMainActivity.Toastflag=false;
                String charString = charSequence.toString();
                if (charString.isEmpty()) {
                    //没有过滤的内容，则使用源数据
                    BookListMainActivity.Toastflag=true;
                    BookListMainActivity.mFilterList = mSourceList;
                } else {
                    List<Book> filteredList = new ArrayList<>();
                    for (int i = 0; i < mSourceList.size(); i++) {
                        if (mSourceList.get(i).getTitle().contains(charString)) {
                            filteredList.add(mSourceList.get(i));
                            BookListMainActivity.bias.add(i);
                        }
                    }
                    BookListMainActivity.mFilterList = filteredList;
                }
                FilterResults filterResults = new FilterResults();
                filterResults.values = BookListMainActivity.mFilterList;
                System.out.println(mSourceList);
                return filterResults;
            }

            //把过滤后的值返回出来
            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                BookListMainActivity.mFilterList = (ArrayList<Book>) filterResults.values;
                notifyDataSetChanged();
            }
        };
    }

    @Override
    public void onClick(View view) {
        if(onItemClickListener!=null){
            int position = recyclerView.getChildAdapterPosition(view);
            //程序执行到此，会执行该方法的具体实现
            onItemClickListener.onItemClick(recyclerView,view,position,BookListMainActivity.mFilterList.get(position));
        }
    }

    @Override
    public void onMove(int fromPosition, int toPosition) {
//        if (fromPosition < toPosition) {
//            for (int i = fromPosition; i < toPosition; i++) {
//                Collections.swap(BookListMainActivity.mFilterList, i, i + 1);
//            }
//        } else {
//            for (int i = fromPosition; i > toPosition; i--) {
//                Collections.swap(BookListMainActivity.mFilterList, i, i - 1);
//            }
//        }
//        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public void onSwiped(int position) {
        Log.i("drag","onSwiped");
        BookListMainActivity.mFilterList.remove(position);
        notifyItemRemoved(position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener{
        //参数（父组件，点击的View，位置，这里可能是某个对象的id或对象/这里不需要）
        void onItemClick(RecyclerView recyclerView, View view, int position, Book obj);
    }
    /**
     *   将RecycleView附加到Adapter上
     */
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.recyclerView= recyclerView;
    }
    /**
     *   将RecycleView从Adapter解除
     */
    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        this.recyclerView = null;
    }

}
